﻿Imports HtmlAgilityPack
Imports System.Data.SQLite

Module Pages

	Public Function GetPage(URL As String, Offline As Boolean) As String
		If Offline Then

			Using conn As New SQLiteConnection(My.Settings.OfflineDataConnectionString)
				conn.Open()
				Dim sql As String = "SELECT HTML FROM PageData WHERE URL=@URL"
				Dim cmd As New SQLiteCommand(sql, conn)

				cmd.Parameters.AddWithValue("@URL", URL)

				Dim page As String = cmd.ExecuteScalar

				If page = "" Then
					page = "<html><body>I don't have that page saved for offline reading.</body><html>"
				End If

				Return page

			End Using

		Else
			Dim page As String = DownloadPage(URL)

			Return page

		End If
	End Function

	Public Function DownloadPage(URL As String) As String
		Dim returnList As New List(Of KeyValuePair(Of String, String))

		Dim pageGetter As New HtmlWeb
		Dim page As String = pageGetter.Load(URL).DocumentNode.OuterHtml

		SavePage(URL, page)

		Return page
	End Function

	Public Sub SavePage(URL As String, page As String)
		Dim allLanguages As List(Of KeyValuePair(Of String, String)) = DownloadLanguages()

		Using conn As New SQLiteConnection(My.Settings.OfflineDataConnectionString)
			conn.Open()
			For Each language In allLanguages
				Dim sql As String = "INSERT OR REPLACE INTO PageData (URL, HTML) VALUES (@URL, @HTML)"
				Dim cmd As New SQLiteCommand(sql, conn)

				cmd.Parameters.AddWithValue("@URL", URL)
				cmd.Parameters.AddWithValue("@HTML", page)

				cmd.ExecuteNonQuery()
			Next

		End Using
	End Sub
End Module
